<?php
namespace app\common\logic;
use app\common\model\Questions;
use app\common\model\QuestionDb;
use app\common\model\Qbank;
use think\Model;
use think\Db;

/* 试题抽取中心类 */
class DrawQuestion extends Model
{
	/* 所有错误提示信息 */
	public $error ='';
	public $ob_ques_model;
	public $ob_qbank_model;
	
	public function __construct(){
		$this->ob_ques_model =  new Questions();
		$this->ob_qbank_model =  new Qbank();
		$this->ob_quesdb_model =  new QuestionDb();
		
		
	}

	public function getError()
	{
		return $this->error;		
	}
	
	public function setError($str){
		$this->error = $str;
	}
	
		/*
	*randomDrawQues 按规则抽题
	*$types 抽题配置
	*$style 返回的类型 0是返回详细 1是返回id
	*$question_bank 确定选择那个题库 0是直接大题库
	*$ratio比例规则
	*/

	public function randomDrawQues($qbankid=0,$ratio='',$style=1){
		//规则格式
		//0:2:2:2  第一位：知识点，第二位：题型。第三位：抽题数量，第四位：分值
		//抽出的题的结果数组
		$question_ids_arr = array();
		
		//获取试卷配置信息
		//$this->ob_ques_model->getInfo($)
		//解析抽题规则为数组
		$ratio_arr = $this->toQuesTypeArr($ratio);
		//var_dump($ratio_arr);
		//对题型进行循环
		//var_dump($ratio_arr);

		//获取题库配置信息
		//$qbankid = 50;
		$qbank_conf = model('Qbank')->getInfo($qbankid);
		$is_main_qbank = $qbank_conf['parentid']==0 ? true :false;
		//var_dump($qbankid);exit;

		foreach($ratio_arr as $key=>$val){

			foreach($val as $t){
				$knows_id = $t[0];
				$ques_type = $t[1];
				$ques_num = $t[2];
				//var_dump('知识点'.$knows_id.'  题型'.$ques_type);
				//获取对应所有题id集合
				$que_all_arr = $this->getQuestionIds($qbankid,$ques_type,$knows_id,$is_main_qbank);

				//抽题数量不为0时，随机抽取规则数量的题ids 0:表示不限制数量显示所有
				if($ques_num>0){
					$que_rand_arr = array_rand($que_all_arr,count($que_all_arr)<=$ques_num ? count($que_all_arr) : $ques_num ); 														
					unset($que_result_arr);
                    if(is_array($que_rand_arr)){
						foreach($que_rand_arr as $v){
						$que_result_arr[] = $que_all_arr[$v];
						}
				   }else{
					   $que_result_arr[] = $que_all_arr[$que_rand_arr];
                   }
				}else{
					$que_result_arr = $que_all_arr;
				}
				
				$temp = $question_ids_arr[$ques_type];
				if(!is_array($temp)) $temp = (array)$temp;
				$question_ids_arr[$ques_type] = array_merge($temp,$que_result_arr);
			}
		}

		
		//如果为1返带文字的详细内容
		if($style==1 || $style==3)	$result = $this->getQuestionsInfo($question_ids_arr,$style,$is_main_qbank);
		//如果为2返回ID数组
		if($style ==2)  $result = $question_ids_arr;
		//var_dump($result);die;
                
		return $result;
	}
	
	/*
	*@func	deRation 解析抽题规则
	*@param	$rstr 规则字符串
	*@param	$backType	1:返回二维带全数组格式 2: 返回字符串格式 3:返回每条规则格式的数组
	*@result 返回数组 
	*/	
	
	public function deRation($rstr,$backType=1){
		if(empty($rstr)) return false;
		$ratio_arr = unserialize($rstr);
        $ratio_arr_temp = '';
		if($backType == 2) {
			foreach($ratio_arr as $key=>$val){
				$ratio_arr_temp .= $val;
				
				if(count($ratio_arr)-1 > $key)	$ratio_arr_temp .=PHP_EOL;
			}
		    return $ratio_arr_temp ;
		
		}else if ($backType == 3){
            foreach($ratio_arr as $val){
                $results[] = explode(',',$val);
            }
            foreach ($results as $xx){
                foreach($xx as $val){
                    $result[] = explode(':',$val);
                }
            }
            return $result;
        }
		foreach($ratio_arr as $val){
		$result[] = explode(':',$val);			
		}
		return $result;			
	}
	
	/*
	*@func	deRation 解析抽题规则
	*@param	$rstr 规则字符串
	*@result 返回数组
	*/	
	
	public function enRation($rstr){
		if(!empty($rstr)){
			$p_ratio_arr = str_replace(PHP_EOL,'|',$rstr);
			$p_ratio_arr = str_replace('\r\n','|',$p_ratio_arr);
			$p_ratio_arr = str_replace('\r','|',$p_ratio_arr);
			$p_ratio_arr = str_replace('\n','|',$p_ratio_arr);
			$p_ratio_arr = str_replace("<br>",'|',$p_ratio_arr);
			$p_ratio_arr = explode('|',$p_ratio_arr);
			$p_ratio_arr_tem = $p_ratio_arr;

			unset($p_ratio_arr);
			//去除空规则
			foreach($p_ratio_arr_tem as $val){
				if(!empty($val)&&$val!='') $p_ratio_arr[]= trim($val);
			}
		}		

		$result = serialize($p_ratio_arr);
		return $result;			
	}
		
	
	/*
	*@func	toQuesTypeArr 转换为题型作为KEY的数组
	*@param	$rstr 规则字符串
	*@result 返回数组
	*/	
	
	public function toQuesTypeArr($arr){

		if(empty($arr)) return false;		
		$ratio_arr = $this->deRation($arr);
		$result = array();
		foreach($ratio_arr as $key=>$val){
			
			$result[$val[1]][] = $val;
			
		}		
		return $result;			
	}
	
	public function getQuestionIds($qbankid,$ques_type,$knows_id,$qbanktype=true){
		
		if($qbanktype) $result = $this->ob_ques_model->getQuestionIds($qbankid,$ques_type,$knows_id,100);
		else
			$result = $this->ob_quesdb_model->getQuestionIds($qbankid,$ques_type,$knows_id,100);
		return $result;
	}
	
	//根据ID获取试题的详细信息
	public function getQuestionsInfo($ids,$style=1,$qbanktype=true){
		//把多维数组转为一维数组，同时对试题ID作为KEY，以便下面直接赋值试题详情。
		foreach($ids as $key=>$val){			
			foreach($val as $v){
				$ids_temp[] = $v;			
			}
			$ids_new[$key] = array_flip($val);
		}
		$ids_temp = array_unique($ids_temp);

		$o =  $qbanktype ? $this->ob_ques_model : $this->ob_quesdb_model;
		$ques = $o->getQuestionsById($ids_temp,'q_typeid asc');

		//试题内容转换到ids数组
		foreach($ques as $val){
            $val['q_select_arr'] = self::exAnswerStrToArr($val['q_select']);
            if ($style==3){
                $result[] = $val;
            }else{
                $result[$val['q_typeid']][] = $val;
            }
		}

		return $result;	
		
	}
	
	/* 规则返解析 */
	
	//function deRation
	

	/* 试题答案规则函数 */
	
	public static function deAnswer($str,$delimiter='!@#'){
		//$str='A.不规则 B.规则 C.完全 D.没有问题';
		if(empty($str)) return false;
		$anIndex =  array('A','B','C','D','E','F','G');
		if(substr_count($str,$delimiter)>0) $arr = explode($anIndex,$delimiter);
		foreach($arr as $val){
			
			$val = str_replace('','',$val);
			$resultArr[] = $val;
		} 
		
	}
	
	/*  
	@function exAnswerStrToArr 试题答案备选项规则解析
	@str param string 解析的字符串
	@delimiter string 分隔符
	@return 以ABCD为键的数组
	*/
	public static function exAnswerStrToArr($str='',$delimiter='#*#'){
		$anIndex =  array('A','B','C','D','E','F','G');		
		//$str = 'A.中国##|B.胡天';
		//有分隔符的情况
		$resultArr = array();
		
		if(substr_count($str,$delimiter)>0) {
			$arr = explode($delimiter,$str);
			foreach($arr as $val){
				$arrTemp = self::exAnswerStrToArrReg($val);					
				$resultArr = array_merge($resultArr,$arrTemp);				
			}			
		}
		//判断机制
		
		if(false=== self::selectAnswerPass($resultArr)) {$resultArr = self::exAnswerStrToArrReg($str);}
		return $resultArr;		
	}

	
	/* 
	@function exStrToArrReg 通过正则解析试题选项 
	@str param string 解析的字符串
	@return 以ABCD为键的数组
	*/
	public static function exAnswerStrToArrReg($str=''){
		$anIndex =  array('A','B','C','D','E','F','G');	

		//临时处理特殊符号，今后写好正则后取消
		$symbols = array('、','？');
		
		foreach($symbols as $val){
			$str = str_replace($val,'.',$str);
		}
		//无分隔的情况 有ABCDE加.的情况
		$arr =  preg_split('/([a-zA-Z]+\.)/',$str,-1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); 
		$resultArr = array();
		$isKey = false; $skey='';
		foreach($arr as $val){
			if($isKey){$resultArr[$skey] = $val;$isKey = false;}
			$val = str_replace('.','',$val);
			$val = str_replace(PHP_EOL,'',$val);
			$val = trim($val);
			if(in_array($val,$anIndex)) {
				$isKey=true;
				$skey=$val;
			}			
		}
		return $resultArr;
	}
	
	/* 
	@function selectAnswerPass 答案是否符合规则函数 
	@arr param array 解析的字符串
	@return 符合规则返回true 否则 false
	*/
	public static function selectAnswerPass($arr){
		
		if(empty($arr)) return false;
		$anIndex =  array('A','B','C','D','E','F','G');		
		$countKey=0;
		$arrKey = array_keys($arr);
		
		foreach($arrKey as $val){
			if(in_array($val,$anIndex)) $countKey++;
		}
		return $countKey<=1 ? false :true;
	}
	
	//获取总题库和分题库的总和
	public function again($practice_list){
		$questions = '';
		$questiondb = '';
		foreach($practice_list as $val){
			if($val['question'] == 1){
				$questions .= $val['question_id'].',';
			}else{
				$questiondb .= $val['question_id'].',';
			}
		}
		$questions = rtrim($questions, ',');
		$questiondb = rtrim($questiondb, ',');
		$ques = $this->ob_ques_model->getQuestionsById($questions);
		$quesdb = $this->ob_quesdb_model->getQuestionsById($questiondb);
		foreach ($ques as $key=>$val){
			$ques[$key]['question'] =1;
		}
		foreach ($quesdb as $key=>$val){
			$quesdb[$key]['question'] =2;
		}
		if(!empty($ques) && !empty($quesdb)) $list = array_merge($ques,$quesdb);
		if(!empty($ques) && empty($quesdb)) $list = $ques;
		if(!empty($quesdb) && empty($ques)) $list =$quesdb;
		return $list ? $list : '';
	}
}	
